<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-form-item label="段别" prop="segmentId">
          <el-select v-model="formData.segmentId" placeholder="请选择段别" style="width: 100%" @change="handleSegmentChange">
            <el-option v-for="item in segmentList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="线别" prop="deptId">
          <treeselect v-model="formData.deptId" :options="deptOptions" :flat="true" :normalizer="normalizer"
                      placeholder="选择线别" style="width: 100%" :default-expand-all="true" @select="handleDeptSelect" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import * as SegmentLineApi from '@/api/lamp/segmentline';
import * as SegmentApi from '@/api/lamp/segment';
import { listDept } from '@/api/system/dept';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "SegmentLineForm",
  components: {
    Treeselect
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        segmentId: undefined,
        segmentName: undefined,
        deptId: undefined,
        deptName: undefined,
      },
      // 表单校验
      formRules: {
        segmentId: [{ required: true, message: '段别不能为空', trigger: 'blur' }],
        deptId: [{ required: true, message: '线别不能为空', trigger: 'blur' }],
      },
      // 段别列表
      segmentList: [],
      // 产线树选项
      deptOptions: []
    };
  },
  created() {
    this.getOptions();
  },
  methods: {
    // 获取下拉框选项
    async getOptions() {
      try {
        // 获取段别列表
        const segmentRes = await SegmentApi.getSegmentPage({ pageSize: 100, pageNo: 1 });
        this.segmentList = segmentRes.data.list;

        // 获取产线列表（线别）
        const deptRes = await listDept({ pageNo: 1, pageSize: 100 });
        this.deptOptions = this.handleTree(deptRes.data, "id");
      } catch (error) {
        this.$message.error('获取选项数据失败');
      }
    },

    // 处理产线树数据
    handleTree(data, id, parentId, children, rootId) {
      id = id || 'id';
      parentId = parentId || 'parentId';
      children = children || 'children';
      rootId = rootId || Math.min.apply(Math, data.map(item => { return item[parentId] })) || 0;
      // 对源数据深度克隆
      const cloneData = JSON.parse(JSON.stringify(data));
      // 循环所有项
      const treeData = cloneData.filter(father => {
        // 返回每一项的子级数组
        const branchArr = cloneData.filter(child => {
          // 匹配子级
          return father[id] === child[parentId];
        });
        branchArr.length > 0 ? father[children] = branchArr : delete father[children];
        // 返回第一层
        return father[parentId] === rootId;
      });
      return treeData !== '' ? treeData : data;
    },

    // 产线树数据格式化（只允许选择type==2的线别）
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children
      };

      // 如果不是type==2的线别，则禁用
      if (node.deptType !== 2) {
        normalizedNode.isDisabled = true;
      }
      return normalizedNode;
    },

    // 处理段别选择变化
    handleSegmentChange(segmentId) {
      const segment = this.segmentList.find(item => item.id === segmentId);
      if (segment) {
        this.formData.segmentName = segment.name;
      }
    },

    // 处理线别选择
    handleDeptSelect(deptId) {
      if (deptId && deptId.name) {
        this.formData.deptName = deptId.name;
      }
    },

    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await SegmentLineApi.getSegmentLine(id);
          this.formData = res.data;
          this.dialogTitle = "修改段别线别绑定";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增段别线别绑定";
      }
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await SegmentLineApi.updateSegmentLine(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await SegmentLineApi.createSegmentLine(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },

    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        segmentId: undefined,
        segmentName: undefined,
        deptId: undefined,
        deptName: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>



<style scoped>
/* 确保所有表单组件宽度一致 */
:deep(.el-input),
:deep(.el-select),
:deep(.vue-treeselect) {
  width: 100% !important;
  box-sizing: border-box;
}
</style>
